package br.com.iswe.teste.dbunit;



import java.io.File;

import javax.sql.DataSource;

import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.datatype.DataType;
import org.dbunit.dataset.datatype.DataTypeException;
import org.dbunit.dataset.datatype.DefaultDataTypeFactory;
import org.dbunit.dataset.excel.XlsDataSet;
import org.dbunit.operation.DatabaseOperation;

/**
 * @author Rafael Almeida
 * @version $Id: ExcelDump.java,v 1.1 2008/09/04 20:27:13 pentateu Exp $
 */
public class ExcelDump {


	protected static Object getDataTypeFactory() {
		return new DefaultDataTypeFactory(){
			public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException
		    {
		        if (sqlTypeName.equals("BOOLEAN"))
		        {
		            return DataType.BOOLEAN;
		        }
		        return super.createDataType(sqlType, sqlTypeName);
		    }

		};
	}

	public static void loadExcelFile(String file, DataSource dataSource) {
		try{
			IDatabaseConnection connection = new DatabaseConnection(dataSource.getConnection());
			DatabaseConfig config = connection.getConfig();
            config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
                   getDataTypeFactory());
			try
			{
				IDataSet dataSet = new XlsDataSet(new File(file));
	            DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
	        }
	        finally
	        {
	            connection.close();
	        }
		}
		catch(Exception exp){
			exp.printStackTrace();
		}

	}

}
